﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Device.Location;
using Microsoft.Phone.Maps.Controls;
using System.Windows.Shapes;
using System.Windows.Media;
using Windows.Devices.Geolocation;
using System.Threading.Tasks;

namespace SMARTMobile.Views
{
    public partial class GheThamPage : PhoneApplicationPage
    {
        private GeoCoordinate MyCoordinate = null;

        private double _accuracy = 0.0;
        private MapLayer myLocationLayer;
        private MapLayer tapLocationLayer;
        private GeoCoordinate tapLocation;
        private bool _isChonViTri;
        private ProgressIndicator _progressIndicator;

        public GheThamPage()
        {
            InitializeComponent();
            //this.Loaded += (s, e) => SystemTray.ProgressIndicator = new ProgressIndicator();
            _progressIndicator = new ProgressIndicator();
            _progressIndicator.IsVisible = true;
            _progressIndicator.IsIndeterminate = true;
            _progressIndicator.Text = "Loading...";
            RadBusyIndicator.IsRunning = true;
            SystemTray.SetProgressIndicator(this, _progressIndicator);
            this.SetProgressIndicator(true);
            myLocationLayer = new MapLayer();
            tapLocationLayer = new MapLayer();
            this.ShowMyLocationOnTheMap(true);
        }

        private void ChonViTriButton_Click(object sender, EventArgs e)
        {
            this._isChonViTri = true;
        }


        private void appBarButton1_Click(object sender, EventArgs e)
        {
            double distanceToMSFT = tapLocation.GetDistanceTo(MyCoordinate);
            MessageBox.Show("It is " + distanceToMSFT.ToString() + " meters from there to Microsoft!");
        }

        private async void ShowMyLocationOnTheMap(bool isGps)
        {
            Geolocator geolocator = new Geolocator();
            //geolocator.DesiredAccuracy = PositionAccuracy.Default;
            //geolocator.DesiredAccuracyInMeters = 50;
            try
            {
                _progressIndicator.Text = "Dang lay thong tin GPS";
                ////Geoposition currentPosition = await geolocator.GetGeopositionAsync();
                // get the async task
                var asyncResult = geolocator.GetGeopositionAsync();
                var task = asyncResult.AsTask();

                // add a race condition - task vs timeout task
                // hardcode to 30s
                var readyTask = await Task.WhenAny(task, Task.Delay(30000));
                if (readyTask != task) // timeout wins
                    throw new TimeoutException();

                if (geolocator.LocationStatus == PositionStatus.Disabled)
                {
                    // Couldn't get current location - location might be disabled in settings
                    MessageBox.Show(
                        "Chức năng định vị (Location) chưa được Bật. Vui lòng Bật chức năng định vị để sử dụng Bản Đồ.");
                    this.SetProgressIndicator(false);
                    RadBusyIndicator.IsRunning = false;
                    isGps = false;
                }
                else
                {
                    // position found within timeout
                    Geoposition currentPosition = await task;
                    MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
                }
            }
            ////catch (Exception ex)
            ////{
            ////// Couldn't get current location - location might be disabled in settings
            ////MessageBox.Show(
            ////    "Chức năng định vị (Location) chưa được Bật. Vui lòng Bật chức năng định vị để sử dụng Bản Đồ.");
            ////this.SetProgressIndicator(false);
            ////RadBusyIndicator.IsRunning = false;
            ////isGps = false;
            ////}
            catch (TimeoutException ex)
            {
                MessageBox.Show("Lấy thông tin GPS tự động quá lâu. Vui lòng chọn Vị Trí lần nữa");
                this.SetProgressIndicator(false);
                RadBusyIndicator.IsRunning = false;
                return;
            }

            if (!isGps)
            {
                isGps = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
                ShowMyLocationOnTheMap(true);
                return;
            }

            this.MyMap.Center = MyCoordinate;
            // Create a small circle to mark the current location.
            Ellipse myCircle = new Ellipse();
            myCircle.Fill = new SolidColorBrush(Colors.Red);
            myCircle.Height = 20;
            myCircle.Width = 20;
            myCircle.Opacity = 50;
            myCircle.Tap += MyCircle_Tap;

            // Create a MapOverlay to contain the circle.
            MapOverlay myLocationOverlay = new MapOverlay();
            myLocationOverlay.Content = myCircle;
            myLocationOverlay.PositionOrigin = new Point(0.5, 0.5);
            myLocationOverlay.GeoCoordinate = MyCoordinate;

            // Create a MapLayer to contain the MapOverlay.
            myLocationLayer.Clear();
            myLocationLayer.Add(myLocationOverlay);

            // Add the MapLayer to the Map.
            // MyMap.Layers.Clear();
            if (MyMap.Layers.Count == 0)
            {
                MyMap.Layers.Add(myLocationLayer);
            }

            this.SetProgressIndicator(false);
            RadBusyIndicator.IsRunning = false;
            // Make my current location the center of the Map.
            ////this.MyMap.Center = MyCoordinate;
            ////this.MyMap.ZoomLevel = 13;

        }

        private void MyCircle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/DSKhachHangPage.xaml?longtitude="
                + this.MyCoordinate.Longitude + "&latitude=" + this.MyCoordinate.Latitude, UriKind.Relative));
        }

        private void MyMap_OnTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this._isChonViTri)
            {
                this._isChonViTri = false;


                tapLocation =
                    MyMap.ConvertViewportPointToGeoCoordinate(e.GetPosition((UIElement)sender));
                // Create a small circle to mark the current location.
                Ellipse myCircle = new Ellipse();
                myCircle.Fill = new SolidColorBrush(Colors.Green);
                myCircle.Height = 20;
                myCircle.Width = 20;
                myCircle.Opacity = 50;

                // Create a MapOverlay to contain the circle.
                MapOverlay myLocationOverlay = new MapOverlay();
                myLocationOverlay.Content = myCircle;
                myLocationOverlay.PositionOrigin = new Point(0.5, 0.5);
                myLocationOverlay.GeoCoordinate = tapLocation;

                tapLocationLayer.Clear();

                // Create a MapLayer to contain the MapOverlay.
                tapLocationLayer.Add(myLocationOverlay);

                // Add the MapLayer to the Map.
                if (!MyMap.Layers.Contains(tapLocationLayer))
                {
                    MyMap.Layers.Add(tapLocationLayer);
                }
            }
        }

        private void SetProgressIndicator(bool value)
        {
            _progressIndicator.IsIndeterminate = value;
            _progressIndicator.IsVisible = value;
        }

        private void LayViTri_Click(object sender, EventArgs e)
        {
            this.ShowMyLocationOnTheMap(true);
        }

        private void GanViTri_Click(object sender, EventArgs e)
        {
            ////if (this.MyCoordinate != null)
            ////{
            ////    NavigationService.Navigate(new Uri("/Views/DSKhachHangPage.xaml?longtitude="
            ////    + this.MyCoordinate.Longitude + "&latitude=" + this.MyCoordinate.Latitude, UriKind.Relative));
            ////}
            _progressIndicator = new ProgressIndicator();
            _progressIndicator.IsVisible = true;
            _progressIndicator.IsIndeterminate = true;
            _progressIndicator.Text = "Loading...";
            RadBusyIndicator.IsRunning = true;
            SystemTray.SetProgressIndicator(this, _progressIndicator);
            this.SetProgressIndicator(true);
            this.ShowMyLocationOnTheMap(true);

        }

        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
        }

        private void ZoomIn_Clicked(object sender, RoutedEventArgs e)
        {
            if (MyMap.ZoomLevel < 20)
            {
                MyMap.ZoomLevel++;
            }
        }
        private void ZoomOut_Clicked(object sender, RoutedEventArgs e)
        {
            if (MyMap.ZoomLevel > 1)
            {
                MyMap.ZoomLevel--;
            }
        }
    }
}